/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.brucexx.wedding.controller;

import java.io.IOException;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.brucexx.wedding.dao.BaseModelDAO;
import com.brucexx.wedding.dao.PermissionDAO;
import com.brucexx.wedding.model.Comment;
import com.brucexx.wedding.model.Story;
import com.brucexx.wedding.util.BeanHelper;
import com.brucexx.wedding.util.DateHelper;
import com.brucexx.wedding.util.NumberHelper;
import com.brucexx.wedding.util.StringHelper;

/**
 * 
 * @author Administrator
 */
@Controller
public class StoryController {

	private static final Log logger = LogFactory.getLog(StoryController.class);

	@RequestMapping(value = "/feng_story.action")
	public String handleFengStory(HttpServletRequest request,
			HttpServletResponse response) throws IOException {

		return "story/fengstory";
	}

	@RequestMapping(value = "/mo_story.action")
	public String handleMoStory(HttpServletRequest request,
			HttpServletResponse response) throws IOException {

		return "story/mostory";
	}

	@RequestMapping(value = "/story_del.action")
	public String storyDel(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		if (!PermissionDAO.isAdmin(request.getSession())) {
			return "admin/no_permission";
		}
		String flag = StringHelper.null2String(request.getParameter("flag"));
		long id = NumberHelper.string2Long(
				StringHelper.null2String(request.getParameter("id")), -1L);

		BaseModelDAO.deleteByID(Story.class, id);
		List<Comment> list = BaseModelDAO.executeSqlForList("select from "
				+ Comment.class.getName() + " where oid=='" + id + "'");

		BaseModelDAO.deleteByID(Comment.class, id);
		BaseModelDAO.deleteList(list);
		if (flag.equals("01")) {
			response.sendRedirect("feng_story.action");
		} else if (flag.equals("02")) {
			response.sendRedirect("mo_story.action");
		}
		return null;
	}

	@RequestMapping(value = "/story_edit.action")
	public String storyEdit(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		if (!PermissionDAO.isAdmin(request.getSession())) {
			return "admin/no_permission";
		}
		return "story/storyedit";
	}

	@RequestMapping(value = "/story_detail.action")
	public String storyDetail(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		long id = NumberHelper.string2Long(
				StringHelper.null2String(request.getParameter("id")), -1L);

		Story story = BaseModelDAO.loadById(id, Story.class);
		story.setBrowseAmount(story.getBrowseAmount() + 1);
		BaseModelDAO.addOrUpdate(story);
		return "story/storydetail";
	}

	@RequestMapping(value = "/story_add.action")
	public String storyAdd(HttpServletRequest request,
			HttpServletResponse response) throws IOException {

		String storyname = StringHelper.null2String(request
				.getParameter("storyname"));
		long id = NumberHelper.string2Long(
				StringHelper.null2String(request.getParameter("id")), -1L);
		String storycontent = StringHelper.null2String(request
				.getParameter("storycontent"));
		String author = PermissionDAO.getRealNameBySession(request.getSession());
		String flag = StringHelper.null2String(request.getParameter("flag"));
		Story story = null;
		if (id != -1) {
			if (!PermissionDAO.isAdmin(request.getSession())) {
				return "admin/no_permission";
			}

			story = BaseModelDAO.loadById(id, Story.class);
			story.setStoryName(storyname);
			story.setStoryContent(storycontent);
			story.setGmtModify(new Date());
			story.setAuthor(author);
		} else {
			story = new Story();
			story.setStoryName(storyname);
			story.setStoryContent(storycontent);
			story.setAuthor(author);
			story.setGmtCreate(new Date());
			story.setGmtModify(new Date());
			story.setFlag(flag);
		}
		BaseModelDAO.addOrUpdate(story);
		if (flag.equals("01")) {
			response.sendRedirect("feng_story.action");
		} else if (flag.equals("02")) {
			response.sendRedirect("mo_story.action");
		} else {
			response.sendRedirect("/");
		}
		return null;
	}

	@RequestMapping(value = "/story.action", method = RequestMethod.GET)
	public void loadPage(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		response.setContentType("text/json");
		response.setCharacterEncoding("UTF-8");
		response.setHeader("Cache-Control", "no-cache");
		String flag = StringHelper.null2String(request.getParameter("flag"));
		int page = NumberHelper.string2Int(request.getParameter("page"), 1) - 1;
		int pageCount = NumberHelper.string2Int(
				request.getParameter("pageCount"), 20);
		int curNum = page * pageCount;

		JSONArray jsonList = new JSONArray();
		String sizeGql = "select from " + Story.class.getName()
		+ "  where flag == '" + flag + "'";
		int totalSize = BaseModelDAO.getCountBySql(sizeGql);
		logger.info("query story gql["+sizeGql+"]totalsize=>"+totalSize);
		int curOffset=0;
		if (totalSize >= (curNum + pageCount)) {
			curOffset =  curNum + pageCount;
		}else{
			curOffset= totalSize;
		}
		String gql = "select from " + Story.class.getName()
				+ "  where flag == '" + flag + "' order by gmtCreate desc ";
		
		List<Story> list = BaseModelDAO.executeSqlForPage(gql, curNum, curOffset);
		JSONObject obj = new JSONObject();
		obj.put("totalCount", totalSize);
		obj.put("pageCount", pageCount);
		jsonList.add(obj);

//		for (int i = curNum; i < curOffset; i++) {
		for(Story story:list){
//			Story story = list.get(i);
			JSONObject tmp = new JSONObject();
			BeanHelper
					.copyProperties2JSON(tmp, story, "gmtModify", "gmtCreate");
			tmp.put("gmtModify", DateHelper.getChinaDateTime(story.getGmtModify()));
			tmp.put("gmtCreate", DateHelper.getChinaDateTime(story.getGmtCreate()));
			jsonList.add(tmp);
		}
		logger.info("load story page str[" + jsonList + "]");
		response.getWriter().write(jsonList.toString());
	}

}
